package com.atguigu.yygh.order.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.component.CancelOrderSender;
import com.atguigu.yygh.common.component.MsmSender;
import com.atguigu.yygh.common.component.SuccessOrderSender;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.enums.OrderStatusEnum;
import com.atguigu.yygh.hosp.client.HospitalFeignClient;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.order.mapper.OrderInfoMapper;
import com.atguigu.yygh.order.service.OrderInfoService;
import com.atguigu.yygh.order.service.WeixinService;
import com.atguigu.yygh.user.client.PatientFeignClient;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.atguigu.yygh.vo.msm.MsmVo;
import com.atguigu.yygh.vo.order.OrderCountQueryVo;
import com.atguigu.yygh.vo.order.OrderCountVo;
import com.atguigu.yygh.vo.order.OrderMqVo;
import com.atguigu.yygh.vo.order.OrderQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author 孔德成
 * @since 2021-09-13
 */
@Service
@Slf4j
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    private final SuccessOrderSender successOrderSender;

    private final PatientFeignClient patientFeignClient;
    private final HospitalFeignClient hospitalFeignClient;
    @Autowired // 这里使用构造器注入会导致循环引用，无法启动服务
    private WeixinService weixin;
    private final CancelOrderSender cancelOrderSender;
    @Autowired
    private MsmSender msmSender;

    public OrderInfoServiceImpl(SuccessOrderSender successOrderSender, PatientFeignClient patientFeignClient, HospitalFeignClient hospitalFeignClient, CancelOrderSender cancelOrderSender) {
        this.successOrderSender = successOrderSender;
        this.patientFeignClient = patientFeignClient;
        this.hospitalFeignClient = hospitalFeignClient;
        this.cancelOrderSender = cancelOrderSender;
    }

    @Override
    public Long saveOrder(String scheduleId, Long patientId) {
        // 1. 获取就诊人信息
        Patient patientOrder = patientFeignClient.getPatientOrder(patientId);
        // 2. 获取排班信息
        ScheduleOrderVo scheduleOrderVo = hospitalFeignClient.getScheduleOrderVo(scheduleId);

        // 3. TODO 指定时间内才可以预约

        // 4. 剩余票数小于等于0抛出异常
        if (scheduleOrderVo.getAvailableNumber() <= 0) {
            throw new YyghException();
        }

        // 5. 创建订单对象，封装参数
        OrderInfo orderInfo = new OrderInfo();
        // 5.1 设置排班数据
        BeanUtil.copyProperties(scheduleOrderVo, orderInfo);
        // 5.2 设置就诊人数据
        orderInfo.setPatientId(patientOrder.getId());
        orderInfo.setPatientName(patientOrder.getName());
        orderInfo.setPatientPhone(patientOrder.getPhone());
        orderInfo.setScheduleId(scheduleId);
        orderInfo.setUserId(patientOrder.getUserId());
        // 订单流水号
        String outTradeNo = System.currentTimeMillis() + "" + new Random().nextInt(100);
        orderInfo.setOutTradeNo(outTradeNo);
        // 订单状态
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
        // 6. 保存到数据库
        this.save(orderInfo);
        // 7. 封装调用医院接口需要传递的参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode", orderInfo.getHoscode());
        paramMap.put("depcode", orderInfo.getDepcode());
        paramMap.put("hosScheduleId", scheduleOrderVo.getHosScheduleId());
        paramMap.put("reserveDate", DateUtil.format(orderInfo.getReserveDate(), "yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount", orderInfo.getAmount());
        paramMap.put("timestamp", System.currentTimeMillis());
//        Map<String, Object> map = BeanUtil.beanToMap(patientOrder);
//        // 该值会导致参数拼接错误的json串，导致fastjson在解析对象时报错
//        map.remove("param");
//        map.put("birthdate",DateUtil.format(patientOrder.getBirthdate(),"yyyy-MM-dd"));
//        paramMap.putAll(map);
        paramMap.put("birthdate", patientOrder.getBirthdate());
        paramMap.put("phone", patientOrder.getPhone());
        paramMap.put("isMarry", patientOrder.getIsMarry());
        paramMap.put("provinceCode", patientOrder.getProvinceCode());
        paramMap.put("cityCode", patientOrder.getCityCode());
        paramMap.put("districtCode", patientOrder.getDistrictCode());
        paramMap.put("address", patientOrder.getAddress());
        //联系人
        paramMap.put("contactsName", patientOrder.getContactsName());
        paramMap.put("contactsCertificatesType", patientOrder.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo", patientOrder.getContactsCertificatesNo());
        paramMap.put("contactsPhone", patientOrder.getContactsPhone());
        // 获取医院签名
        String sign = hospitalFeignClient.getSignKey(scheduleOrderVo.getHoscode());
        paramMap.put("sign", sign);
        // 查询 apiurl
        String apiUrl = hospitalFeignClient.getApiUrl(scheduleOrderVo.getHoscode());
        // 8. 请求医院预约下单接口
        String response = HttpUtil.post(apiUrl + "/order/submitOrder", HttpUtil.toParams(paramMap));
        JSONObject result = JSONObject.parseObject(response);
        if (result.getInteger("code") == 200) {
            JSONObject jsonObject = result.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = jsonObject.getString("hosRecordId");
            //预约序号
            Integer number = jsonObject.getInteger("number");
            //取号时间
            String fetchTime = jsonObject.getString("fetchTime");
            //取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");
            //更新订单
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            baseMapper.updateById(orderInfo);
            //排班可预约数
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            //排班剩余预约数
            Integer availableNumber = jsonObject.getInteger("availableNumber");


            // 号源数据
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId);
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setAvailableNumber(availableNumber);

            // 短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            msmVo.setTemplateCode("预约下单");
            orderMqVo.setMsmVo(msmVo);

            // 向下单成功队列发送消息，更新号源
            successOrderSender.sendMessage(orderMqVo);
        } else {
            // 下单失败
            log.error("下单失败");
            throw new YyghException(20001, "下单失败");
        }
        return orderInfo.getId();
    }

    @Override
    public IPage<OrderInfo> selectPage(Page<OrderInfo> pageParam, OrderQueryVo orderQueryVo) {
        // orderQueryVo 获取条件值
        // 医院名称
        String name = orderQueryVo.getKeyword();
        // 就诊人名称
        Long patientId = orderQueryVo.getPatientId();
        // 订单状态
        String orderStatus = orderQueryVo.getOrderStatus();
        // 用户id
        Long userId = orderQueryVo.getUserId();
        // 安排时间
        String reserveDate = orderQueryVo.getReserveDate();
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();
        //对条件值进行非空判断
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(name)) {
            wrapper.like("hosname", name);
        }
        if (ObjectUtil.isNotEmpty(patientId)) {
            wrapper.eq("patient_id", patientId);
        }
        if (ObjectUtil.isNotEmpty(userId)) {
            wrapper.eq("user_id", userId);
        }
        if (StrUtil.isNotBlank(orderStatus)) {
            wrapper.eq("order_status", orderStatus);
        }
        if (StrUtil.isNotBlank(reserveDate)) {
            wrapper.ge("reserve_date", reserveDate);
        }
        if (StrUtil.isNotBlank(createTimeBegin)) {
            wrapper.ge("create_time", createTimeBegin);
        }
        if (StrUtil.isNotBlank(createTimeEnd)) {
            wrapper.le("create_time", createTimeEnd);
        }
        if (StrUtil.isNotBlank(createTimeEnd)) {
            wrapper.le("create_time", createTimeEnd);
        }

        // 调用mapper的方法
        IPage<OrderInfo> pages = baseMapper.selectPage(pageParam, wrapper);
        //编号变成对应值封装
        pages.getRecords().forEach(item -> {
            item.getParam().put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(item.getOrderStatus()));
        });
        return pages;
    }

    @Override
    public OrderInfo getOrderInfo(Long id) {
        OrderInfo orderInfo = baseMapper.selectById(id);
        orderInfo.getParam().put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        return orderInfo;
    }

    @Override
    public Boolean cancelOrder(Long orderId) {
        // 1. 查询预约下单记录
        OrderInfo orderInfo = this.getById(orderId);
        // // 2. 超过退号时间，无法取消预约
        // if (DateUtil.compare(DateTime.now(), orderInfo.getQuitTime()) > 0) {
        //     throw new YyghException(20001, "已超过退号时间");
        // }

        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode", orderInfo.getHoscode());
        reqMap.put("hosRecordId", orderInfo.getHosRecordId());
        reqMap.put("timestamp", System.currentTimeMillis());
        // TODO 签名校验
        reqMap.put("sign", "");

        // 3. 调用医院的更新取消预约状态接口,将医院系统用户订单状态修改为取消预约状态
        String post = HttpUtil.post("http://localhost:9998/order/updateCancelStatus", reqMap);
        JSONObject result = JSONObject.parseObject(post);
        // 4. 取消预约失败处理
        if (result.getInteger("code") != 200) {
            throw new YyghException(ResultCodeEnum.FAIL.getCode(), result.getString("message"));
        } else {
            // 5. 取消预约成功处理
            // 5.1 如果平台订单状态为已支付，则需要退款
            if (orderInfo.getOrderStatus().intValue() == OrderStatusEnum.PAID.getStatus().intValue()) {
                if (!weixin.refund(orderId)) {
                    // 退款申请失败
                    throw new YyghException(20001, "退款申请失败");
                }
            }
            // 6. 更改平台订单状态
            orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
            this.updateById(orderInfo);
            // 7. 退款成功处理
            // 7.1 更新平台预约数，剩余预约数+1
            OrderMqVo orderMqVo = new OrderMqVo();
            // 设置排班id
            orderMqVo.setScheduleId(orderInfo.getScheduleId());
            // 短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            msmVo.setTemplateCode("取消预约");
            orderMqVo.setMsmVo(msmVo);
            cancelOrderSender.sendMessage(orderMqVo);
        }
        return true;
    }

    /**
     * 就诊提醒：
     * 查询今日预约就诊的订单，获取就诊人信息，对每个就诊人发送就诊提醒
     */
    @Override
    public void patientTips() {
        // 1. 查询今日所有预约订单
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        String format = DateUtil.format(DateUtil.date(), "yyyy-MM-dd");
        log.info(format);
        queryWrapper.eq("reserve_date", format);
        List<OrderInfo> orderInfoList = baseMapper.selectList(queryWrapper);
        log.info(orderInfoList.toString());
        for (OrderInfo orderInfo : orderInfoList) {
            // 2. 向每个就诊人发送一则提醒就诊短信
            MsmVo msmVo = new MsmVo();
            // 就诊人手机号
            msmVo.setPhone(orderInfo.getPatientPhone());
            // 短信模版
            msmVo.setTemplateCode("就诊提醒");
            String reserveDate = DateUtil.format(orderInfo.getReserveDate(), "yyyy-MM-dd") + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
            Map<String, Object> param = new HashMap<String, Object>() {{
                // 标题
                put("title", orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle());
                // 预约日期
                put("reserveDate", reserveDate);
                // 就诊人姓名
                put("name", orderInfo.getPatientName());
            }};
            msmVo.setParam(param);
            // 3. 将短信发送到短信队列中，待短信队列接收者接收后，执行发送短信操作
            msmSender.sendMessage(msmVo);
        }
    }


    @Override
    public Map<String, Object> getCountMap(OrderCountQueryVo orderCountQueryVo) {
        Map<String, Object> map = new HashMap<>();

        List<OrderCountVo> orderCountVoList
                = baseMapper.selectOrderCount(orderCountQueryVo);
        //日期列表
        List<String> dateList
                = orderCountVoList.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());
        //统计列表
        List<Integer> countList
                = orderCountVoList.stream().map(OrderCountVo::getCount).collect(Collectors.toList());
        map.put("dateList", dateList);
        map.put("countList", countList);
        return map;
    }
}
